package tabletask

import (
	"crypto/sha1"
	"encoding/hex"
	"io"
	"io/ioutil"
	"os"
	"time"

	"cvevulner/cve-timed-task/db_models"
	"cvevulner/cve-timed-task/downloadfiletask"
	"cvevulner/cve-timed-task/util"
	"cvevulner/models"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

// import excel
func ImportData() {
	ormModel := orm.NewOrm()
	filePath, err := downloadfiletask.HandleFour()
	if err != nil {
		logs.Error("downloadfiletask.HandleFour error:", err)
		return
	}

	files, err := ioutil.ReadDir(filePath)
	if err != nil {
		logs.Error(" ioutil.ReadDir error: ", err, filePath)
		return
	}

	for _, file := range files {
		fileName := file.Name()
		if file.IsDir() {
			logs.Warn(filePath+fileName, "is Dir, remove")
			_ = os.RemoveAll(filePath + fileName)
			continue
		}
		f, err := os.Open(filePath + fileName)
		if err != nil {
			continue
		}
		hash := sha1.New()
		_, err = io.Copy(hash, f)
		if err != nil {
			logs.Error("io.Copy :", err)
			_ = f.Close()
			continue
		}
		_ = f.Close()
		sum := hash.Sum(nil)
		hashValue := hex.EncodeToString(sum)
		logs.Info("open transaction")
		tranErr := ormModel.Begin()
		if tranErr != nil {
			logs.Error(" Open transaction error:", tranErr.Error())
			continue
		}
		list, rowsAffected, err := db_models.SelectCveFileHashByFileName(fileName, ormModel)
		if err != nil {
			logs.Error("db_models.SelectCveFileHashByFileName :", err)
			tranErr = ormModel.Rollback()
			if tranErr != nil {
				logs.Error(" Rollback transaction error:", tranErr.Error())
			}
			continue
		}
		if rowsAffected > 0 && util.InSlice(list, hashValue) {
			logs.Info("file has been parsed", fileName)
			tranErr = ormModel.Rollback()
			if tranErr != nil {
				logs.Error(" Rollback transaction error:", tranErr.Error())
			}
			_ = os.Remove(filePath + fileName)
			continue
		}
		err = db_models.InsertCveFileHash(fileName, hashValue, ormModel)
		if err != nil {
			logs.Error("db_models.InsertCveFileHash :", err)
			tranErr = ormModel.Rollback()
			if tranErr != nil {
				logs.Error(" Rollback transaction error:", tranErr.Error())
			}
			continue
		}
		tranErr = ormModel.Commit()
		if tranErr != nil {
			logs.Error(" Commit transaction error:", tranErr.Error())
			continue
		}
		excel, err := excelize.OpenFile(filePath + fileName)
		if err != nil {
			logs.Error("excelize.OpenReader:", err)
			continue
		}

		rows, err := excel.GetRows("Sheet1")
		if err != nil {
			logs.Error("excel.GetRows Sheet1 error", err)
			continue
		}
		now := time.Now().Format("2006-01-02 15:04:05")
		var packName string
		var assignee string
		for _, row := range rows[1:] {
			if len(row) < 1 || row[0] == "" {
				continue
			}
			packName = row[0]

			if len(row) > 1 {
				assignee = row[1]
			} else {
				assignee = ""
			}
			err = db_models.InsertSpecIssueAssigness(&models.SpecIssueAssigness{
				PackageName: packName,
				Assignee:    assignee,
				Status:      1,
				CreateTime:  now,
			}, ormModel)
			if err != nil {
				logs.Error(err)
				continue
			}
		}
		_ = os.Remove(filePath + fileName)
	}

}
